<template>
  <div class="carbon-credit-page">

    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <el-row :gutter="20" class="filter-row">
        <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center">
            <span class="filter-label">核证标准</span>
            <el-select
              v-model="form.certificationCriteria"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
            >
              <el-option v-for="item in certificationCriteria" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center">
            <span class="filter-label">领域</span>
            <el-select
             v-model="form.fieldCode"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
            >
            <el-option v-for="item in projectScope" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center">
            <span class="filter-label">状态</span>
            <el-select
             v-model="form.projectStatus"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
            >
            <el-option v-for="item in projectStatus" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center">
            <span class="filter-label">行业</span>
            <el-select
             v-model="form.industry"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
            >
            <el-option v-for="item in industory" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="filter-item" style="display: flex; align-items: center; gap: 10px;">
            <span class="filter-label">立项日期</span>
            <el-date-picker
              v-model="form.initiationDateStart"
              style="flex: 1;"
              type="date"
              placeholder="开始时间"
              clearable
              class="filter-date"
            ></el-date-picker>
            <span style="white-space: nowrap;">至</span>
            <el-date-picker
              v-model="form.initiationDateEnd"
              style="flex: 1;"
              type="date"
              placeholder="结束时间"
              clearable
              class="filter-date"
            ></el-date-picker>
          </div>
        </el-col>
      </el-row>

      <!-- 第二行搜索 -->
      <el-row :gutter="20" class="search-row" style="margin-top: 10px">
        <el-col :span="8">
          <div style="display: flex;" class="filter-item">
            <span style="margin-top: 8px;" class="filter-label2">按项目搜索</span>
            <div class="search-container">
              <el-input
                v-model="form.projectName"
                placeholder="输入项目名称"
                clearable
                class="search-input"
                style="flex: 1"
                @keyup.enter.native="handleProjectSearch"
              ></el-input>
              <el-button type="success" plain @click="handleProjectSearch"
                >查询</el-button
              >
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div style="display: flex;" class="filter-item2">
            <span style="margin-top: 8px;" class="filter-label2">方法学搜索</span>
            <div class="search-container">
              <el-input
                v-model="form.mName"
                placeholder="输入方法学名称"
                clearable
                class="search-input"
                @keyup.enter.native="handleMethodSearch"
              ></el-input>
              <el-button type="success" plain @click="handleMethodSearch"
              >查询</el-button
              >
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格数据区域 -->
    <div class="table">
      <el-table
        :data="tableData"
        stripe
        @selection-change="handleSelectionChange"
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="id" label="序号" align="center" width="80"></el-table-column>
        <el-table-column
          prop=""
          label="备案号" 
          show-overflow-tooltip
          width="110"
        ></el-table-column>
        <el-table-column
          prop="projectName"
          label="项目名称" 
          show-overflow-tooltip
          width="210"
        ></el-table-column>
        <el-table-column
          prop="certificationCriteria"
          label="核证标准" 
          align="left"
          show-overflow-tooltip
          width="200"
        ></el-table-column>
        <el-table-column
          prop="projectScope"
          label="领域" 
          width="110"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="industry"
          label="行业" 
          width="130"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="projectStatus"
          label="状态" 
          align="center"
          width="140"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
        prop="ownerName"
          label="业主名称" 
          align="center"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="initiationDate"
          label="立项日期" 
          align="center"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="approvalDate"
          label="审定日期" 
          align="center"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="recordFilingDate"
          label="备案日期" 
          align="center"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="certifiedDate"
          label="核证日期" 
          align="center"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="issuingDate"
          label="签发日期" 
          align="center"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="recordFilingReduction"
          label="备案减排量" 
          align="center"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template v-slot="scope">
            <div class="operation-btns">
               <span 
                class="btn-text view" 
                @click="handleView(scope.row.id)"
              >查看</span>
              <span 
                class="btn-text doc" 
                @click="handleDoc(scope.row.id)"
              >文档</span>
               <span 
                class="btn-text sp" 
                @click="sp(scope.row.id)" v-if="scope.row.projectStatus === '待审核'"
              >审批</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination" v-if="mainTotal > 0">
        <el-pagination
          background
          @current-change="handleMainPageChange"
          @size-change="handleMainPageSizeChange"
          :current-page="mainPageNum"
          :page-size="mainPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-count="mainTotalPages"
          :page-sizes="[5, 10, 15, 20]"
        ></el-pagination>
      </div>
    </div>
        

  </div>
</template>

<script>

export default {
  name: "projectDo",
  data() {
    return {
    // spView : false,
      id :'',
      // 领域
      projectScope: [],
      // 核证机构
      certificationCriteria: [],
      // 产业类型
      industory: [],
      // 项目状态
      projectStatus: [],
    //备案减排量
     recordFilingReduction:'',

      tableData: [],
      mainPageNum: 1,       // 主表格当前页码
      mainPageSize: 10,     // 主表格每页条数
      mainTotal: 0,         // 总记录数
      tableLoading: false,  // 表格加载状态
      user: JSON.parse(localStorage.getItem('user') || '{}'),
      selectedProjects: [], // 选中的项目

      form: {
        certificationCriteria: '', // 核证标准
        projectName: '',           // 项目名称（搜索用）
        mName: '',                 // 方法学名称
        fieldCode: '',             // 领域
        industry: '',             // 行业
        status: '',                // 状态
        initiationDateStart: '',   // 立项日期开始
        initiationDateEnd: '',      // 立项日期结束
        projectStatus:''
      },
    };
  },


computed: {
  
    mainTotalPages() {
    if (this.mainTotal <= 0) return 0;
    return Math.ceil(this.mainTotal / this.mainPageSize);
  },
  },

  mounted() {
    this.queryProjects();
    this.loadSelectorData();
  },

  methods:{

      // 重置分页
      resetMainPagination() {
        this.mainPageNum = 1;
        this.queryProjects();
      },

      // 项目搜索
      handleProjectSearch() {
        this.mainPageNum = 1;
        this.queryProjects();
      },

      // 方法学搜索
      handleMethodSearch() {
        this.mainPageNum = 1;
        this.queryProjects();
      },

      // 处理页码变化
      handleMainPageChange(val) {
        this.mainPageNum = val;
        this.queryProjects();
      },

      // 处理每页条数变化
      handleMainPageSizeChange(val) {
        this.mainPageSize = val;
        this.mainPageNum = 1;
        this.queryProjects();
      },
   
      // 格式化日期为YYYY-MM-DD
      formatDate(date) {
        if (!date) return '';
        const d = new Date(date);
        return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
      },

      queryProjects() {
      this.tableLoading = true;
      
      const params = {
        ...this.form,

        pageNum: this.mainPageNum,      // 添加当前页码
        pageSize: this.mainPageSize  // 添加每页条数
      };

      // 处理状态默认值
      if (params.status === '0040000000') {
        params.status = null;
      }

      // 处理默认值为空的情况
      if (params.certificationCriteria === '0070000000') {
        params.certificationCriteria = null;
      }
      if (params.industory === '0020000000') {
          params.industory = null;
      }
      if (params.fieldCode === '0030000000') {
          params.fieldCode = null;
      }
      // 处理日期格式
      if (params.initiationDateStart) {
        params.initiationDateStart = this.formatDate(params.initiationDateStart);
      }
      if (params.initiationDateEnd) {
        params.initiationDateEnd = this.formatDate(params.initiationDateEnd);
      }

      this.$request.get('/assets/carbonProject/queryBySelector', {
        params: params
      }).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          this.tableData = res.data.records || [];
          this.mainTotal = res.data.total || 0;
        }
      }).catch(error => {
        this.tableLoading = false;
        console.error("查询项目列表失败:", error);
      });
    },
   

      handleView(id) {
      this.$router.push({
    path: '/carbon/projectCreate/projectDetail',
    query: { id: id } // 通过query传递参数，与详情页的this.$route.query.id对应
  })
      //location.href = '/carbon/projectCreate/projectDetail?id=' + id
    },

    handleDoc(id) {
      // 文档操作逻辑
      this.$router.push({
        path: '/sys/metaregistrydoc',
      query: { projectId:id       
     } 
      })
    },
    sp(id){
        this.id = id
        this.$confirm('您确定通过该项目吗？', '确认通过', { type: "warning" }).then(response => {
            this.$request.post('/assets/carbonProject/addStatus', 
            {}, 
             {params: { 
                id: this.id,
                 } 
             }
            ).then(res=>{
        if(res.code === 200){
            this.$message.success(res.msg)
            this.resetUploadForm()
            this.queryProjects()
            
        }
      })
      })
    },


    resetUploadForm(){
            this.id = null
            this.recordFilingReduction = null
            this.spView = false
    },
      loadSelectorData() {
      this.$request.get('/assets/carbonCreditAssets/querySelector').then(res => {
        if (res.code === 200) {
          this.certificationCriteria = res.data.certificationList
          this.projectScope = res.data.projectScopeList
          this.industory = res.data.industoryList
          this.projectStatus = res.data.projectStatusList 
        }
      })
    },

    handleSelectionChange(selection) {
      // 处理选择变化
      this.selectedProjects = selection;
    }
  }
}
</script>

<style lang="scss" scoped>
.carbon-credit-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

/* 筛选区域样式 */
.filter-section {
  background: #f8f9fa;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .filter-row,
  .search-row {
    display: flex;
    flex-wrap: wrap;
  }

  .filter-item {
    margin-bottom: 10px;
  }

  .filter-label {
    display: inline-block;
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;
    min-width: 60px;
  }

  .filter-label2 {
    display: inline-block;
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;
    width: 150px;
  }

  .filter-select,
  .filter-date {
    width: 100%;
    --el-input-border-color: #dcdfe6;
  }

  .search-container {
    display: flex;
    align-items: center;
    width: 100%;
  }

  .search-input {
    flex: 1;
    margin-right: 10px;
    --el-input-border-color: #dcdfe6;
  }
}

/* 操作按钮样式 */
.operation-btns {
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: center;

  .btn-text {
    cursor: pointer;
    &.view {
      color: #409eff;
    }
    &.doc {
      color: #67c23a;
    }&.sp {
      color: #d37415;
    }
    &:hover {
      text-decoration: underline;
    }
  }
}

/* 表格样式 */
.table {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>